package mrpanyu.guitool.image;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.OnParameterChange;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;
import net.ifok.image.image4j.codec.ico.ICOEncoder;

@ToolModel(displayName = "图片转ICO文件")
public class IcoConverter {

	@Parameter(displayName = "输入图片", description = "支持JPG/PNG格式", type = ParameterType.FILE, order = 1)
	private File imgFile;

	@Parameter(displayName = "输出文件", type = ParameterType.FILE, order = 2)
	private File outputFile;

	@OnParameterChange("imgFile")
	public void onImgFileChange(Tool tool) throws Exception {
		if (imgFile != null) {
			String imgPath = imgFile.getCanonicalPath();
			int idx = imgPath.lastIndexOf('.');
			String outputPath = imgPath;
			if (idx > 0) {
				outputPath = imgPath.substring(0, idx);
			}
			outputPath += ".ico";
			this.outputFile = new File(outputPath);
		}
	}

	@Action(displayName = "转换为ICO", order = 1)
	public void convert(Tool tool) throws Exception {
		tool.clearMessages();
		if (imgFile == null || outputFile == null) {
			tool.errorMessage("请选择输入输出文件");
			return;
		} else if (!imgFile.isFile()) {
			tool.errorMessage("文件不存在: " + imgFile);
			return;
		}
		BufferedImage img = ImageIO.read(imgFile);
		outputFile.getParentFile().mkdirs();
		ICOEncoder.write(img, outputFile);
		tool.infoMessage("已生成文件: " + outputFile);
	}

}
